package com.apes.fn.server.productRequireManage.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.productRequireManage.model.ReplenishmentBusinessImpAbstract;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("repleDumpSumItemService")
public class RepleDumpSumItemService extends ReplenishmentBusinessImpAbstract {

    @Autowired
    private ProductUomRepository productUomRepository;

    @Override
    public JSONObject sumRequireItem(JSONObject getJO) {
        // 根据要货单和仓库分组汇总
        StringBuffer needDumpRequireIdStr = new StringBuffer();
        Map<JSONObject, List<Object>> groupbyRequireItem = getJO.getJSONArray("item").stream().collect(Collectors.groupingBy(item -> {
            JSONObject itemObj = (JSONObject) item;
            String productRequireId = itemObj.getString("productRequireId");
            String uomId = itemObj.getJSONObject("uom").getString("id");
            String productId = itemObj.getJSONObject("product").getString("id");
            String locationId = itemObj.getJSONObject("location").getString("id");
            needDumpRequireIdStr.append(this.judgeExistsRequireId(productRequireId, needDumpRequireIdStr.toString()));
            return new JSONObject(MapUtil.mapper("productId", productId, "locationId", locationId, "uomId", uomId));
        }));

        // 根据分组后的数据循环汇总明细缺货数量
        JSONObject returnData = new JSONObject();
        returnData.put("allRequireId", needDumpRequireIdStr.toString());
        returnData.put("sumProductRequireItems", this.appendDumpGapData(groupbyRequireItem));
        return returnData;
    }

    // 要货缺口转转储数据
    private JSONArray appendDumpGapData(Map<JSONObject, List<Object>> groupbyRequireItem) {
        JSONArray dumpGapDataArray = new JSONArray();
        groupbyRequireItem.forEach((k, v) -> {

            // 获取相同商品所有的缺口
            double sumGapQty = this.sumGapQty(v);
            if (sumGapQty <= 0) return;

            JSONObject itemObj = (JSONObject) v.get(0);
            JSONObject dumpSumDataObj = new JSONObject();
            dumpSumDataObj.put("customerExpand", itemObj.get("customerExpand"));
            dumpSumDataObj.put("location", itemObj.getJSONObject("location"));
            dumpSumDataObj.put("locationCompany", itemObj.getJSONObject("locationCompany"));
            dumpSumDataObj.put("product", itemObj.getJSONObject("product"));
            dumpSumDataObj.put("canAssignableQty", 0);
            dumpSumDataObj.put("distributionQty", 0);

            ProductUom requireUom = productUomRepository.findOne(k.getLong("uomId"));
            ProductUom dumpUom = requireUom;
            if (!requireUom.isTransferFirst()) {
                dumpUom = productUomRepository.findByProductId(k.getString("productId"));
            }

            double toBeReplenishedQty = Math.ceil(requireUom.computeQty(sumGapQty, dumpUom, false));
            dumpSumDataObj.put("toBeReplenishedQty", toBeReplenishedQty);
            dumpSumDataObj.put("uom", MapUtil.mapper("id", dumpUom.getId(), "name", dumpUom.getName()));
            dumpSumDataObj.put("requireUom", itemObj.getJSONObject("uom"));
            dumpGapDataArray.add(dumpSumDataObj);
        });
        return dumpGapDataArray;
    }

    // 过滤已选择且缺口大于 0 的
    private double sumGapQty(List v) {
        return v.stream().filter(item -> ((JSONObject) item).getBooleanValue("selectFlag")).mapToDouble(item -> {
            JSONObject itemObj = (JSONObject) item;
            double requireQty = itemObj.getDoubleValue("qtyRequire");
            double assignedQty = itemObj.getDoubleValue("qtyAssigned");
            double endQty = itemObj.getDoubleValue("qtyEnded");
            double orderQty = itemObj.getDoubleValue("orderQty");
            double endResultQty = requireQty - assignedQty - endQty - orderQty;
            return endResultQty > 0?endResultQty:0;
        }).sum();
    }

    // 返回需要转储的要货单
    private String judgeExistsRequireId(String requireId, String needDumpRequireIdStr) {
        return StringUtils.isEmpty(needDumpRequireIdStr) || needDumpRequireIdStr.indexOf(requireId + ",") == -1?requireId + ",":"";
    }


    public JSONObject obtainStock(JSONObject getJO) {
        JSONObject fLocation = getJO.getJSONObject("location");

        String fCompayId = fLocation.getJSONObject("company").getString("id");
        String fLocationId = fLocation.getString("id");

        Map<JSONObject, List<Object>> groupRequires = this.itemGroup(getJO, fCompayId);

        groupRequires.forEach((k, v) -> {
            String productId = k.getString("productId");

            // 获取可用数
            double usableQty = 0;
            try {
                usableQty = this.obtainStockUsableQty(k.getString("reception"), fLocationId, productId, null);
            } catch (Exception e) {
                return;
            }


            double[] canAssignableQty = {usableQty}; // 需要查看不同商品过来时会不会影响其他商品的值
            for (int i = 0, iLen = v.size(); i < iLen; i++) {
                JSONObject requireItemObj = (JSONObject) v.get(0);
                requireItemObj.put("canAssignableQty", canAssignableQty);
                requireItemObj.put("backupCanAssignableQty", usableQty); // 存储最原始的分配数

                if (usableQty <= 0) break;

                double toBeReplenishedQty = requireItemObj.getDoubleValue("toBeReplenishedQty");
                if (usableQty <= toBeReplenishedQty) {
                    requireItemObj.put("distributionQty", usableQty);
                    usableQty = 0;
                } else if (usableQty > toBeReplenishedQty) {
                    requireItemObj.put("distributionQty", toBeReplenishedQty);
                    usableQty -= toBeReplenishedQty;
                }
                canAssignableQty[0] = usableQty;
            }
        });
        return getJO;
    }

    // 按商品、收货仓库运营模式、是否跨公司分组
    private Map<JSONObject, List<Object>> itemGroup(JSONObject getJO, String FlocationCompayId) {
        return getJO.getJSONArray("sumProductRequireItems").stream().collect(Collectors.groupingBy(item -> {
            JSONObject itemObj = (JSONObject) item;
            String locationId = itemObj.getJSONObject("location").getString("id");
            String subCompanyId = itemObj.getJSONObject("locationCompany").getString("id");
            String reception = invoke("scm.transferProductService.accordLCompanyChangeOperation", MapUtil.mapper("id", locationId));
            return new JSONObject(MapUtil.mapper("productId", itemObj.getJSONObject("product").getString("id"),
                    "reception", reception,
                    "subCompanyId", subCompanyId,
                    "isNotCross", FlocationCompayId.equals(subCompanyId)));
        }));
    }



}























